<template>
  <view class="home-page">
    <!-- 自定义导航栏 -->
    <view class="home-header" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <view class="location-selector">
        <text>{{ currentCity }}</text>
        <uni-icons type="down" size="16" color="#333"></uni-icons>
      </view>
      <view class="search-bar" @click="gotoSearch">
        <uni-icons type="search" size="18" color="#888"></uni-icons>
        <text class="placeholder">日常保洁、深度除螨...</text>
      </view>
    </view>

    <!-- 页面内容，需要设置上边距以避开自定义导航栏 -->
    <scroll-view class="scroll-content" :scroll-y="true" :style="{ paddingTop: headerHeight + 'px' }">
      <!-- 轮播图 -->
      <view class="carousel-section">
        <swiper class="carousel" circular autoplay :interval="3000" :duration="500" @change="onSwiperChange">
          <swiper-item v-for="item in swiperList" :key="item.id">
            <image :src="item.imageUrl" class="carousel-image" mode="aspectFill"></image>
          </swiper-item>
        </swiper>
        <view class="dots">
          <view v-for="(item, index) in swiperList" :key="item.id" class="dot" :class="{ active: index === currentSwiperIndex }"></view>
        </view>
      </view>

      <!-- 热门推荐 -->
      <view class="content-section">
        <view class="section-header">
          <h2 class="section-title">热门推荐</h2>
          <view class="see-all" @click="seeAllServices">
            <text>查看全部</text>
            <uni-icons type="right" size="14" color="#888"></uni-icons>
          </view>
        </view>
        <view class="service-grid">
          <view v-for="service in hotServices" :key="service.id" class="service-card" @click="gotoServiceDetail(service.id)">
            <image :src="service.image" class="service-image" mode="aspectFill"></image>
            <view class="service-info">
              <text class="service-title">{{ service.title }}</text>
              <text class="service-subtitle">{{ service.subtitle }}</text>
              <view class="service-meta">
                <view class="service-price">
                  <text class="symbol">¥</text>
                  <text class="amount">{{ service.price }}</text>
                  <text class="unit">/{{ service.unit }}</text>
                </view>
                <text class="service-orders">{{ service.orderCount }}+人下单</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
import { useSystemInfo } from '@/composables/useSystemInfo';
import { request } from '@/utils/request.js';
import { BASE_URL } from '@/utils/config.js';

// 使用自定义Hook获取系统信息，用于适配顶部安全区域
const { safeAreaInsets, headerHeight } = useSystemInfo();

// ---- 响应式状态定义 ----
const currentCity = ref('上海');
const swiperList = ref([]);      // 轮播图列表，初始为空
const currentSwiperIndex = ref(0); // 当前轮播图索引
const hotServices = ref([]);     // 热门服务列表，初始为空

// ---- API 请求方法 ----

/**
 * @description 获取轮播图数据
 */
const fetchSwiperData = async () => {
  try {
    const data = await request({
      url: '/carousels',
      method: 'GET',
    });
    // 数据转换：将后端返回的数据映射为前端需要的格式
    swiperList.value = data.map(item => ({
      id: item.carouselId, // 注意后端字段可能是 a_b 形式，需要前端处理或后端统一
      imageUrl: `${BASE_URL}${item.imageUrl}`, // 拼接完整的图片URL
    }));
  } catch (error) {
    console.error('获取轮播图数据失败:', error);
    // 可选：在这里处理错误，例如显示一个默认的轮播图
    swiperList.value = []; // 清空以防显示旧数据
  }
};

/**
 * @description 获取热门服务列表
 */
const fetchHotServices = async () => {
  try {
    const data = await request({
      url: '/hotServices',
      method: 'POST',
      data: {
        serviceNumber: 4 // 获取4个热门服务
      }
    });
    // 数据转换：将后端返回的数据映射为前端需要的格式
    hotServices.value = data.map(item => ({
      id: item.serviceId,
      title: item.serviceMainName,
      subtitle: item.serviceSubName,
      // 关键: 拼接图片URL。请确保/profile/是正确的静态资源访问路径
      image: `${BASE_URL}${item.serviceHeadImg}`, 
      price: item.serviceMoney.toFixed(2),
      unit: '次', // 注意: 您的接口未返回单位，暂时硬编码
      orderCount: item.serviceCount,
    }));
  } catch (error) {
    console.error('获取热门服务失败:', error);
    hotServices.value = []; // 清空以防显示旧数据
  }
};

/**
 * @description 加载页面所有核心数据
 */
const loadData = () => {
  // 并行发起两个请求，提升加载速度
  Promise.all([fetchSwiperData(), fetchHotServices()]);
};


// ---- 事件处理方法 ----

/**
 * @description 轮播图切换时更新指示点
 */
const onSwiperChange = (e) => {
  currentSwiperIndex.value = e.detail.current;
};

/**
 * @description 跳转到搜索页 (预留)
 */
const gotoSearch = () => {
  uni.showToast({ title: '搜索功能开发中', icon: 'none' });
};

/**
 * @description 跳转到服务分类 Tab
 */
const seeAllServices = () => {
  uni.switchTab({ url: '/pages/category/category' });
};

/**
 * @description 跳转到服务详情页
 * @param {number} id - 服务ID
 */
const gotoServiceDetail = (id) => {
  uni.navigateTo({ url: `/pages/service-detail/service-detail?id=${id}` });
};


// ---- 生命周期钩子 ----

// 页面加载时执行
onLoad(() => {
  loadData();
});

// 用户执行下拉刷新时执行
onPullDownRefresh(() => {
  // 下拉刷新时重新加载数据
  loadData().finally(() => {
    uni.stopPullDownRefresh(); // 停止下拉刷新动画
  });
});

</script>

<style lang="scss" scoped>
.home-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: $uni-bg-color;
}

.home-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 15rpx 30rpx;
  background-color: $uni-bg-color-white;
}

.location-selector {
  display: flex;
  align-items: center;
  font-size: 30rpx;
  font-weight: 500;
  flex-shrink: 0;
}

.search-bar {
  flex-grow: 1;
  display: flex;
  align-items: center;
  gap: 16rpx;
  height: 68rpx;
  padding: 0 20rpx;
  background-color: $uni-bg-color;
  border-radius: 34rpx;
  .placeholder {
    font-size: 28rpx;
    color: $uni-text-color-placeholder;
  }
}

.scroll-content {
  flex: 1;
  background-color: $uni-bg-color;
  box-sizing: border-box;
}

.carousel-section {
  position: relative;
  margin: 30rpx 30rpx 0;
}

.carousel {
  height: 320rpx;
  border-radius: 24rpx;
  overflow: hidden;
}

.carousel-image {
  width: 100%;
  height: 100%;
}

.dots {
  position: absolute;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 16rpx;
  .dot {
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.6);
    transition: all 0.3s;
    &.active {
      background-color: $uni-bg-color-white;
      width: 30rpx;
    }
  }
}

.content-section {
  padding: 0 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 40rpx 0 30rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: 500;
}

.see-all {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: $uni-text-color-light;
}

.service-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.service-card {
  background-color: $uni-bg-color-white;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.07);
  
  .service-image {
    width: 100%;
    height: 335rpx; // 固定高度，保持1:1比例
  }
  
  .service-info {
    padding: 24rpx;
  }
  
  .service-title {
    display: block;
    font-size: 30rpx;
    font-weight: 500;
    margin-bottom: 8rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .service-subtitle {
    display: block;
    font-size: 24rpx;
    color: $uni-text-color-light;
    margin-bottom: 20rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .service-meta {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
  }
  
  .service-price {
    color: $uni-primary;
    .symbol {
      font-size: 24rpx;
    }
    .amount {
      font-size: 32rpx;
      font-weight: bold;
    }
    .unit {
      font-size: 24rpx;
    }
  }
  
  .service-orders {
    font-size: 24rpx;
    color: $uni-text-color-light;
  }
}
</style>